<template>
  <el-dialog
    v-model="roleDialogVisible"
    title="Warning"
    width="30%"
    align-center
    @close="handleClose"
  >
    <el-form ref="formRef" :model="roleForm.date" label-width="100px">
      <el-checkbox-group v-model="roleForm.date.checkedUserRoles">
        <el-checkbox
          v-for="role in roleForm.date.roleList"
          :id="role.id"
          :key="role.id"
          :label="role.id"
          name="checkedUserRoles"
          >{{ role.name }}</el-checkbox
        >
      </el-checkbox-group>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { defineProps, reactive, ref, watch } from "vue";
import requestUtil from "@/util/request.js";
import { ElMessage } from "element-plus";

//接收父类传入的开启状态
const props = defineProps({
  roleDialogVisible: {
    type: Boolean,
    default: false,
    required: true,
  },
  id: {
    type: String,
    default: "",
    required: true,
  },
  checkedUserRoles: {
    type: Array,
    default: [],
    required: true,
  },
});

const formRef = ref(null);
const roleForm = reactive({
  date: {
    checkedUserRoles: [],
    roleList: [],
    id: "",
  },
});
//初始化数据  配合watch
const initRoles = async (id) => {
  const res = await requestUtil.get("role/roleList");
  roleForm.date.id = id;
  roleForm.date.roleList = res.data.roleList;
};

//关闭Dialog handler
const emits = defineEmits(["update:modelValue", "initDate"]);
let handleClose = () => {
  emits("update:modelValue", false);
};

let handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await requestUtil.post(
        `user/grantRole/${roleForm.date.id}`,
        roleForm.date.checkedUserRoles
      );
      if (res.code == 20000) {
        ElMessage.success("执行成功！");
        emits("initDate");
        handleClose();
      } else {
        ElMessage.error(res.message);
      }
    } else {
      console.log("fail");
    }
  });
};

// 通过监听器 自定注入id
watch(
  () => props.roleDialogVisible,
  () => {
    roleForm.date.checkedUserRoles = []; //每次初始化 防止集合二次利用
    let id = props.id;
    if (id != "") {
      props.checkedUserRoles.forEach((item) => {
        roleForm.date.checkedUserRoles.push(item.id);
      });
      initRoles(id);
    }
  }
);
</script>
<style lang="sass" scoped>
</style>